/*
 Xern Entity Relocation Network
 Copyright (C) 2010-2011 Ronie Salgado <roniesalg@gmail.com>

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/

#include "Xern/Exceptions.hpp"
#include "Xern/Entity.hpp"
#include "RigidBody.hpp"
#include "IBulletShape.hpp"

namespace XernBullet
{

	RigidBody::RigidBody(RigidBodyType type, float mass,
			boost::shared_ptr<ICollisionShape> shape,
			boost::shared_ptr<Entity> target)
		: type(type), shape(shape), target(target)
	{
		// Get the collision shape.
		boost::shared_ptr<IBulletShape> bulletShape =
				boost::dynamic_pointer_cast<IBulletShape> (shape);
		if(!bulletShape)
			throw XernException("Invalid collision shape.");

		btCollisionShape *bshape = bulletShape->GetBulletShape();

		// Read the transform.
		const ReversibleTransform &trans = target->GetWorldTransform();
		Vector3 position = trans.GetVector();
		Quaternion rotation = trans.GetRotation();
		transform.setOrigin(btVector3(position.x, position.y, position.z));
		transform.setRotation(btQuaternion(rotation.x, rotation.y, rotation.z, rotation.w));

		// Create the rigid body.
		btVector3 inertia = btVector3(0,0,0);
		if(mass > 0.0f)
			bshape->calculateLocalInertia(mass, inertia);
		body = new btRigidBody(mass, this, bshape, inertia);
		body->setUserPointer(this);
	}

	RigidBody::~RigidBody()
	{
		delete body;
	}

	IRigidBody::RigidBodyType RigidBody::GetType() const
	{
		return type;
	}

	float RigidBody::GetMass() const
	{
		return 1.0/body->getInvMass();
	}

	boost::shared_ptr<ICollisionShape> RigidBody::GetCollisionShape() const
	{
		return shape;
	}

	boost::shared_ptr<Entity> RigidBody::GetTargetEntity() const
	{
		return target.lock();
	}

	const ReversibleTransform &RigidBody::GetTransform() const
	{
		return localTransform;
	}

	void RigidBody::SetTransform(const ReversibleTransform &trans)
	{
		// Store the transform.
		localTransform = trans;

		// Update the rigid body.
		const Vector3 &pos = trans.GetVector();
		const Quaternion &rot = trans.GetRotation();
		transform.setOrigin(btVector3(pos.x, pos.y, pos.z));
		transform.setRotation(btQuaternion(rot.x, rot.y, rot.z, rot.w));
		if(body)
			body->setWorldTransform(transform);

		// Lock the entity.
		boost::shared_ptr<Entity> ent = target.lock();
		if(ent)
		{
			ent->SetTransform(trans);
		}
	}

	void RigidBody::SetLinearVelocity(const Vector3 &vel)
	{
		body->setLinearVelocity(btVector3(vel.x, vel.y, vel.z));

		// Lock the entity.
		boost::shared_ptr<Entity> ent = target.lock();
		if(ent)
		{
			// Update the entity linear velocity.
			ent->SetLinearVelocity(vel);
		}
	}

	Vector3 RigidBody::GetLinearVelocity() const
	{
		const btVector3 &ret = body->getLinearVelocity();
		return Vector3(ret.x(), ret.y(), ret.z());
	}

	void RigidBody::SetAngularVelocity(const Vector3 &vel)
	{
		body->setAngularVelocity(btVector3(vel.x, vel.y, vel.z));
	}

	Vector3 RigidBody::GetLinearAcceleration() const
	{
		const btVector3 &ret = body->getInvMass()*body->getTotalForce();
		return Vector3(ret.x(), ret.y(), ret.z());
	}

	Vector3 RigidBody::GetAngularVelocity() const
	{
		const btVector3 &ret = body->getAngularVelocity();
		return Vector3(ret.x(), ret.y(), ret.z());
	}

	void RigidBody::SetLinearFactor(const Vector3 &factor)
	{
		body->setLinearFactor(btVector3(factor.x, factor.y, factor.z));
	}

	Vector3 RigidBody::GetLinearFactor() const
	{
		const btVector3 &ret = body->getLinearFactor();
		return Vector3(ret.x(), ret.y(), ret.z());
	}

	void RigidBody::SetAngularFactor(const Vector3 &factor)
	{
		body->setAngularFactor(btVector3(factor.x, factor.y, factor.z));
	}

	Vector3 RigidBody::GetAngularFactor() const
	{
		const btVector3 &ret = body->getAngularFactor();
		return Vector3(ret.x(), ret.y(), ret.z());
	}

	void RigidBody::SetSleepingThresholds(float linear, float angular)
	{
		body->setSleepingThresholds(linear, angular);
	}

	void RigidBody::GetSleepingThresholds(float &linear, float &angular) const
	{
		linear = body->getLinearSleepingThreshold();
		angular = body->getAngularSleepingThreshold();
	}

	void RigidBody::getWorldTransform(btTransform &worldTrans) const
	{
		worldTrans = transform;
	}

	void RigidBody::setWorldTransform(const btTransform &worldTrans)
	{
		// Store the transform.
		transform = worldTrans;

		// Lock the entity.
		boost::shared_ptr<Entity> ent = target.lock();
		if(ent)
		{
			// Get the position.
			btVector3 position = transform.getOrigin();

			// Get the rotation.
			btQuaternion rotation = transform.getRotation();

			// Create the xern transform.
			OrthoTransform xtrans;
			xtrans.SetVector(Vector3(position.x(), position.y(), position.z()));
			xtrans.SetMatrix(QRotMatrix3(Quaternion(rotation.w(), rotation.x(), rotation.y(), rotation.z())));

			// Update the transform.
			localTransform = xtrans;
			ent->SetTransform(xtrans);

			// Update the linear velocity.
			btVector3 vel = body->getLinearVelocity();
			ent->SetLinearVelocity(Vector3(vel.x(), vel.y(), vel.z()));

			// Update the linear acceleration.
			btVector3 accel = body->getInvMass()*body->getTotalForce();
			ent->SetLinearAcceleration(Vector3(accel.x(), accel.y(), accel.z()));

			// Update the angular velocity
			vel = body->getAngularVelocity();
			ent->SetAngularVelocity(Vector3(vel.x(), vel.y(), vel.z()));
		}
	}

	boost::shared_ptr<RigidBody> RigidBody::GetSelf()
	{
		return shared_from_this();
	}

	void RigidBody::updateAction( btCollisionWorld* collisionWorld, btScalar deltaTimeStep)
	{
		boost::shared_ptr<Entity> ent = target.lock();
		if(ent)
			ent->PhysicAction(deltaTimeStep);
	}

	void RigidBody::debugDraw(btIDebugDraw* debugDrawer)
	{
	}

	btRigidBody *RigidBody::GetBulletBody()
	{
		return body;
	}
}; // namespace XernBullet
